//
//  MKUIPickerViewTreeNode.m
//  MKUI
//
//  Created by sushangjin on 15/6/19.
//  Copyright (c) 2015年 sushangjin. All rights reserved.
//

#import "MKUIPickerViewTreeNode.h"

@implementation MKUIPickerViewTreeNode
- (NSString *)description{
	return [NSString stringWithFormat:@"%@,cellModel=%@",[super description],self.cellModel];
}
- (id)initWithTitle:(NSString *)title{
	MKUIPickerViewTreeCellModel *cm = [[MKUIPickerViewTreeCellModel alloc] initWithTitle:title];
	if (self=[self initWithCellModel:cm]) {
	}
	return self;
}
- (id)initWithCellModel:(MKUIPickerViewTreeCellModel *)cellModel{
	if (self=[super init]) {
		self.cellModel = cellModel;
		cellModel.node = self;
	}
	return self;
}
- (NSInteger)indexOfChildNodeWithTitle:(NSString *)title{
	NSInteger index = [self.class indexOfNodeWithTitle:title nodes:self.childrenNodes];
	return index;
}
+ (NSInteger)indexOfNodeWithTitle:(NSString *)title nodes:(NSArray *)nodes{
	if(!title||nodes.count==0)return NSNotFound;
	NSInteger index = [nodes indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
		MKUIPickerViewTreeNode *node = (MKUIPickerViewTreeNode *)obj;
		if([title isEqualToString:node.cellModel.title]){
			*stop = YES;
			return YES;
		}
		return NO;
	}];
	return index;
}
@end

@implementation MKUIPickerViewTreeNode(JSON)
- (void)addChildNodesWithJson:(id)json{
	if([json isKindOfClass:[NSDictionary class]]){
		[self addChildNodesWithDictionary:(NSDictionary *)json];
	}else if([json isKindOfClass:[NSArray class]]){
		[self addChildNodesWithArray:(NSArray *)json];
	}else{
		MKUIPickerViewTreeNode *node = [[MKUIPickerViewTreeNode alloc] initWithTitle:[json description]];
		node.isLeaf = YES;
		[self addChildNode:node];
	}
}
- (void)addChildNodesWithDictionary:(NSDictionary *)json{
	for (id key in json) {
		id val = json[key];
		NSString *title = [key description];
		MKUIPickerViewTreeNode *node = [[MKUIPickerViewTreeNode alloc] initWithTitle:title];
		node.isLeaf = NO;
		if([val isKindOfClass:[NSArray class]]){
			[node addChildNodesWithArray:(NSArray *)val];
		}else if([val isKindOfClass:[NSDictionary class]]){
			[node addChildNodesWithDictionary:(NSDictionary *)val];
		}else{
			MKUIPickerViewTreeNode *subNode = [[MKUIPickerViewTreeNode alloc] initWithTitle:[val description]];
			subNode.isLeaf = YES;
			[node addChildNode:subNode];
		}
		[self addChildNode:node];
	}
}
- (void)addChildNodesWithArray:(NSArray *)json{
	for (id val in json) {
		if([val isKindOfClass:[NSArray class]]){
			[self addChildNodesWithArray:(NSArray *)val];
		}else if([val isKindOfClass:[NSDictionary class]]){
			[self addChildNodesWithDictionary:(NSDictionary *)val];
		}else{
			MKUIPickerViewTreeNode *node = [[MKUIPickerViewTreeNode alloc] initWithTitle:[val description]];
			node.isLeaf = YES;
			[self addChildNode:node];
		}
	}
}
@end
